/*
 * Copyright (c) 2020 WildFireChat. All rights reserved.
 */

package com.cincc.cinccimdemo.qrcode;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.ui.IMBaseActivity;
import com.google.zxing.Result;
import com.king.zxing.CaptureHelper;
import com.king.zxing.Intents;
import com.king.zxing.ViewfinderView;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;

import java.io.InputStream;
import java.util.ArrayList;


public class ScanQRCodeActivity extends IMBaseActivity {

    private CaptureHelper mCaptureHelper;
    SurfaceView surfaceView;
    ViewfinderView viewfinderView;

    private static final int REQUEST_CODE_IMAGE = 100;

    protected void bindViews() {
        super.bindViews();
        surfaceView = findViewById(R.id.surfaceView);
        viewfinderView = findViewById(R.id.viewfinderView);
    }

    @Override
    protected int contentLayout() {
        return R.layout.scan_qrcode_activity;
    }

    @Override
    protected void afterViews() {
        mCaptureHelper = new CaptureHelper(this, surfaceView, viewfinderView);
        mCaptureHelper.onCreate();
        mCaptureHelper.vibrate(true)
                .fullScreenScan(true)//全屏扫码
                .supportVerticalCode(false)//支持扫垂直条码，建议有此需求时才使用。
                .continuousScan(false);
    }

    @Override
    protected int menu() {
        return R.menu.qrcode;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.gallery) {
            applyPermission();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    int REQUEST_CODE_SCAN_QR_CODE = 1207;

    private void applyPermission() {
        String[] permissions = new String[1];

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
                getTargetSdkVersion() >= Build.VERSION_CODES.TIRAMISU) {
            permissions[0] = Manifest.permission.READ_MEDIA_IMAGES;
        } else {
            permissions[0] = Manifest.permission.READ_EXTERNAL_STORAGE;
        }
        if (!checkPermission(permissions)) {
            requestPermissions(permissions, REQUEST_CODE_SCAN_QR_CODE);
        } else {
            scanGalleryQRCode();
        }
    }

    private int getTargetSdkVersion() {
        try {
            PackageManager packageManager = getPackageManager();
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
            return applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1; // 获取失败时返回-1或其他适当的值
        }
    }

    private void scanGalleryQRCode() {
        Intent intent = ImagePicker.picker().showCamera(false).buildPickIntent(this);
        startActivityForResult(intent, REQUEST_CODE_IMAGE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCaptureHelper.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCaptureHelper.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCaptureHelper.onDestroy();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mCaptureHelper.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == Activity.RESULT_OK) {

            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images != null && images.size() > 0) {
                String path = images.get(0).path;

                InputStream is = null;
                Result result = QRCodeHelper.decodeQR(path);
                Intent intent = new Intent();
                if (result == null) {
                    Toast.makeText(this, "识别二维码失败", Toast.LENGTH_SHORT).show();
                } else {
                    intent.putExtra(Intents.Scan.RESULT, result.getText());
                    setResult(Activity.RESULT_OK, intent);
                }
                finish();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_SCAN_QR_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                scanGalleryQRCode();
            } else {
                Toast.makeText(this, "打开权限失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
